#!/usr/bin/python
import os
import sys
import datetime
import socket
import ConfigParser
from base import *

'''读取配置信息'''
conf = ConfigParser.ConfigParser()
conf.read('svnsync.conf')
HOST = conf.get('bind','host')
PORT = int(conf.get('bind','port'))

base_dir = conf.get('info','base_dir')
authfile = conf.get('info','auth_file')
passfile = conf.get('info','pass_file')
key = conf.get('info','key')

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

if __name__ == "__main__":
    '''监听本地端口'''
    try:
        s.bind((HOST,PORT))
    except socket.error,msg:
        print "Bind failed Error Code is:" + str(msg[0]) + "Message:" + msg[1]
        sys.exit()
    
    
    s.listen(10)
                                      
    while True:
        conn,addr = s.accept()
        recv_data = conn.recv(1024)

        if recv_data.split('-')[0] == key:
        #if not recv_data:
        #    print "NO data recved"
        #    sys.exit()
        #else:
        #    print recv_data

            realauth = base_dir + authfile
            auth_md5 = md5sum(realauth) #获取authz文件的md5值
            realpass = base_dir + passfile
            pass_md5 = md5sum(realpass) #获取passwd文件的md5值
            
            send_data_list = [] 

            if recv_data.split('-')[1] == auth_md5:
                send_data_list.append('0') #如果收到的md5值和当前的md5值一样，返回值设为0，不更新
            else:
                send_data_list.append('1') #相反,如果收到的md5值和当前的md5值不一样，返回值设为1，需要更新

            if recv_data.split('-')[2] == pass_md5:
                send_data_list.append('0')
            else:
                send_data_list.append('1')

            send_data = key + '-' + str(send_data_list[0]) + '-' + str(send_data_list[1]) #将相应的返回值返回给client

            conn.sendall(send_data)
        else:
            conn.sendall("wrong key") #如果key不对，报错，防止被恶意攻击

        conn.close()

    s.close()
